#import "MyCLController.h"
@implementation MyCLController
@synthesize locationManager;
@synthesize delegate;
@synthesize currentLocation;

- (id) init
{
	self = [super init];
	if (self != nil) {
		self.locationManager = [[[CLLocationManager alloc] init] autorelease];
		self.locationManager.delegate = self; // send loc updates to myself
	}
	return self;
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{
    if ([delegate respondsToSelector:@selector(locationUpdate:)]) {
        [delegate locationUpdate:newLocation];
    }
    accuracy = newLocation.horizontalAccuracy;
    self.currentLocation = newLocation;
    //NSLog(@"locationManager didUpdateToLocation, accuracy = %lf", accuracy);
    // 精度小于1000米 就停止
    if (accuracy <= BEST_ACCURACY) {
        [self.locationManager stopUpdatingLocation];
        if ([delegate respondsToSelector:@selector(locationFinished:)]) {
            [delegate locationFinished:newLocation];
        }
		[NSObject cancelPreviousPerformRequestsWithTarget:self];
    }
}

- (void)locationManager:(CLLocationManager *)manager
	   didFailWithError:(NSError *)error
{
    if ([delegate respondsToSelector:@selector(locationError:)]) {
        [delegate locationError:error];
    }
}

- (void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
	[locationManager release];
	[currentLocation release];
    [super dealloc];
}

-(void)timeOver
{
	//NSLog(@"MyCLController timeOver");
    // 超时也停止
    [self.locationManager stopUpdatingLocation];
    if ([delegate respondsToSelector:@selector(locationTimeOut:)]) {
        [delegate locationTimeOut:currentLocation];
    }
}

-(void)startLocate
{
	[locationManager startUpdatingLocation];
    [self performSelector:@selector(timeOver) withObject:nil afterDelay:MAX_TIME];
}

-(void)stopLocate
{
    //NSLog(@"locationManager stopLocate ");
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [locationManager stopUpdatingLocation];
    if ([delegate respondsToSelector:@selector(locationFinished:)]) {
        [delegate locationFinished:currentLocation];
    }
	
}
@end

